﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using rehabilitation.Data;
using rehabilitation.Models;

namespace rehabilitation.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PatientController : ControllerBase
    {
        private readonly AppDbContext _context;

        public PatientController(AppDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 1. 通过医生 ID 查询患者列表（支持分页）
        /// </summary>
        [HttpGet("list/{doctorId}")]
        public async Task<IActionResult> GetPatientsByDoctorId(int doctorId, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex < 1 || pageSize < 1)
            {
                return BadRequest("分页参数无效");
            }

            var query = from dp in _context.DoctorPatients
                        join p in _context.Patients on dp.PatientId equals p.Id
                        where dp.DoctorId == doctorId
                        select p;

            int totalRecords = await query.CountAsync();
            var patients = await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();

            return Ok(new
            {
                TotalRecords = totalRecords,
                PageIndex = pageIndex,
                PageSize = pageSize,
                Data = patients
            });
        }

        /// <summary>
        /// 2. 删除患者（仅解除医患关系，不删除患者数据）
        /// </summary>
        [HttpDelete("{doctorId}/{patientId}")]
        public async Task<IActionResult> RemovePatient(int doctorId, int patientId)
        {
            var relation = await _context.DoctorPatients
                .FirstOrDefaultAsync(dp => dp.DoctorId == doctorId && dp.PatientId == patientId);

            if (relation == null)
            {
                return NotFound("医患关系不存在");
            }

            _context.DoctorPatients.Remove(relation);
            await _context.SaveChangesAsync();
            return Ok("患者已解除绑定");
        }

        /// <summary>
        /// 3. 新增患者（并绑定到医生）
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddPatient([FromBody] AddPatientRequest request)
        {
            var existingPatient = await _context.Patients
                .FirstOrDefaultAsync(p => p.Phone == request.Patient.Phone);

            if (existingPatient == null)
            {
                request.Patient.CreateTime = DateTime.Now;
                _context.Patients.Add(request.Patient);
                await _context.SaveChangesAsync();
                existingPatient = request.Patient;
            }

            // 绑定患者到医生
            if (!await _context.DoctorPatients.AnyAsync(dp => dp.DoctorId == request.DoctorId && dp.PatientId == existingPatient.Id))
            {
                _context.DoctorPatients.Add(new DoctorPatient
                {
                    DoctorId = request.DoctorId,
                    PatientId = existingPatient.Id
                });
                await _context.SaveChangesAsync();
            }

            return Ok("患者添加成功");
        }

        /// <summary>
        /// 4. 编辑患者信息
        /// </summary>
        [HttpPut("update")]
        public async Task<IActionResult> UpdatePatient([FromBody] Patient patient)
        {
            var existingPatient = await _context.Patients.FindAsync(patient.Id);
            if (existingPatient == null)
            {
                return NotFound("患者不存在");
            }

            existingPatient.Name = patient.Name;
            existingPatient.Sex = patient.Sex;
            existingPatient.Age = patient.Age;
            existingPatient.Phone = patient.Phone;
            existingPatient.Avatar = patient.Avatar;
            existingPatient.Remark = patient.Remark;

            await _context.SaveChangesAsync();
            return Ok("患者信息更新成功");
        }
    }

    /// <summary>
    /// 用于新增患者请求
    /// </summary>
    public class AddPatientRequest
    {
        public int DoctorId { get; set; }
        public Patient Patient { get; set; }
    }
}
